package handlers

import (
	"domain-system/services"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// ApiResp 统一API响应格式
type ApiResp struct {
	ErrCode int         `json:"errCode"`
	ErrMsg  string      `json:"errMsg"`
	ErrDlt  string      `json:"errDlt"`
	Data    interface{} `json:"data"`
}

// 成功响应辅助函数
func successResponse(data interface{}) ApiResp {
	return ApiResp{
		ErrCode: 0,
		ErrMsg:  "",
		ErrDlt:  "",
		Data:    data,
	}
}

// 错误响应辅助函数
func errorResponse(errCode int, errMsg string, errDlt string) ApiResp {
	return ApiResp{
		ErrCode: errCode,
		ErrMsg:  errMsg,
		ErrDlt:  errDlt,
		Data:    nil,
	}
}

// AuthHandler 认证处理器
type AuthHandler struct {
	authService *services.AuthService
}

// NewAuthHandler 创建认证处理器实例
func NewAuthHandler(db *gorm.DB, jwtSecret string, openIMService *services.OpenIMService) *AuthHandler {
	return &AuthHandler{
		authService: services.NewAuthService(db, jwtSecret, openIMService),
	}
}

// Register 用户注册
func (h *AuthHandler) Register(c *gin.Context) {
	var req services.RegisterRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, errorResponse(400, "请求参数错误", err.Error()))
		return
	}

	response, err := h.authService.Register(&req)
	if err != nil {
		c.JSON(http.StatusOK, errorResponse(400, err.Error(), ""))
		return
	}

	c.JSON(http.StatusCreated, successResponse(map[string]interface{}{
		"message": "注册成功",
		"user":    response,
	}))
}

// RegisterByEmail 邮箱注册
func (h *AuthHandler) RegisterByEmail(c *gin.Context) {
	var req services.RegisterByEmailRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, errorResponse(400, "请求参数错误", err.Error()))
		return
	}

	response, err := h.authService.RegisterByEmail(&req)
	if err != nil {
		c.JSON(http.StatusOK, errorResponse(400, err.Error(), ""))
		return
	}

	c.JSON(http.StatusCreated, successResponse(map[string]interface{}{
		"message": "注册成功",
		"user":    response,
	}))
}

// Login 用户登录
func (h *AuthHandler) Login(c *gin.Context) {
	var req services.LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"status":  "error",
			"message": "请求参数错误",
			"error":   err.Error(),
		})
		return
	}

	response, err := h.authService.Login(&req)
	if err != nil {
		c.JSON(http.StatusOK, errorResponse(401, err.Error(), ""))
		return
	}

	c.JSON(http.StatusOK, successResponse(response))
}

// SendVerificationCode 发送验证码
func (h *AuthHandler) SendVerificationCode(c *gin.Context) {
	var req struct {
		Phone    string `json:"phone" binding:"required"`
		AreaCode string `json:"area_code" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, errorResponse(10001, "请求参数错误", err.Error()))
		return
	}

	// 在SendVerificationCode方法中
	err := h.authService.SendVerificationCode(req.Phone, req.AreaCode)
	if err != nil {
		c.JSON(http.StatusOK, errorResponse(10003, err.Error(), ""))
		return
	}

	c.JSON(http.StatusOK, successResponse(map[string]string{
		"message": "验证码发送成功",
	}))
}

// SendEmailVerificationCode 发送邮箱验证码
func (h *AuthHandler) SendEmailVerificationCode(c *gin.Context) {
	var req struct {
		Email string `json:"email" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, errorResponse(10001, "请求参数错误", err.Error()))
		return
	}

	err := h.authService.SendEmailVerificationCode(req.Email)
	if err != nil {
		c.JSON(http.StatusBadRequest, errorResponse(10003, err.Error(), ""))
		return
	}

	c.JSON(http.StatusOK, successResponse(map[string]string{
		"message": "邮箱验证码发送成功",
	}))
}

// LoginWithVerificationCode 验证码登录
func (h *AuthHandler) LoginWithVerificationCode(c *gin.Context) {
	var req services.VerificationCodeLoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"status":  "error",
			"message": "请求参数错误",
			"error":   err.Error(),
		})
		return
	}

	response, err := h.authService.LoginWithVerificationCode(&req)
	if err != nil {
		c.JSON(http.StatusUnauthorized, errorResponse(401, err.Error(), ""))
		return
	}
	c.JSON(http.StatusOK, successResponse(response))
}

// Logout 用户注销
func (h *AuthHandler) Logout(c *gin.Context) {
	userID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"status":  "error",
			"message": "未授权访问",
		})
		return
	}

	err := h.authService.Logout(userID.(string))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"status":  "error",
			"message": "注销失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"status":  "success",
		"message": "注销成功",
	})
}

// GetProfile 获取用户资料
func (h *AuthHandler) GetProfile(c *gin.Context) {
	userID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"status":  "error",
			"message": "未授权访问",
		})
		return
	}

	user, err := h.authService.GetUserByID(userID.(string))
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"status":  "error",
			"message": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"status": "success",
		"data":   user,
	})
}

// DeactivateAccount 注销账户
func (h *AuthHandler) DeactivateAccount(c *gin.Context) {
	userID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"status":  "error",
			"message": "未授权访问",
		})
		return
	}

	err := h.authService.DeactivateUser(userID.(string))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"status":  "error",
			"message": "账户注销失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"status":  "success",
		"message": "账户已注销",
	})
}

// JWTMiddleware JWT认证中间件
func (h *AuthHandler) JWTMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.JSON(http.StatusUnauthorized, gin.H{
				"status":  "error",
				"message": "缺少认证令牌",
			})
			c.Abort()
			return
		}

		// 检查Bearer前缀
		tokenParts := strings.Split(authHeader, " ")
		if len(tokenParts) != 2 || tokenParts[0] != "Bearer" {
			c.JSON(http.StatusUnauthorized, gin.H{
				"status":  "error",
				"message": "认证令牌格式错误",
			})
			c.Abort()
			return
		}

		// 验证令牌
		userID, err := h.authService.ValidateJWT(tokenParts[1])
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{
				"status":  "error",
				"message": "无效的认证令牌",
			})
			c.Abort()
			return
		}

		// 设置用户ID到上下文
		c.Set("user_id", userID)
		c.Next()
	}
}

// CheckVerificationCode 验证码检测
func (h *AuthHandler) CheckVerificationCode(c *gin.Context) {
	var req struct {
		Phone            string `json:"phone" binding:"required"`
		VerificationCode string `json:"verification_code" binding:"required"`
		AreaCode         string `json:"area_code" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, errorResponse(10001, "请求参数错误", err.Error()))
		return
	}

	// 目前直接返回成功，后续可以添加实际的验证逻辑
	// 可以调用 h.authService.ValidateVerificationCode(req.VerificationCode) 进行验证

	c.JSON(http.StatusOK, successResponse(map[string]string{
		"message": "验证码验证成功",
	}))
}

// CheckEmailVerificationCode 邮箱验证码检测
func (h *AuthHandler) CheckEmailVerificationCode(c *gin.Context) {
	var req struct {
		Email            string `json:"email" binding:"required"`
		VerificationCode string `json:"verification_code" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, errorResponse(10001, "请求参数错误", err.Error()))
		return
	}

	// 目前直接返回成功，后续可以添加实际的验证逻辑
	// 可以调用 h.authService.ValidateEmailVerificationCode(req.Email, req.VerificationCode) 进行验证

	c.JSON(http.StatusOK, successResponse(map[string]string{
		"message": "邮箱验证码验证成功",
	}))
}

// ResetPassword 重置密码
func (h *AuthHandler) ResetPassword(c *gin.Context) {
	var req services.ResetPasswordRequest

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, errorResponse(400, "请求参数错误", err.Error()))
		return
	}

	resp, err := h.authService.ResetPassword(&req)
	if err != nil {
		c.JSON(http.StatusOK, errorResponse(400, "重置密码失败", err.Error()))
		return
	}

	c.JSON(http.StatusOK, successResponse(resp))
}
